package login

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"management/database"
	"management/jwt"
	"management/util"
	"net/http"
)

func InitLogin(g *gin.Engine) {
	// 用户登录
	g.POST("/login", func(c *gin.Context) {
		name := c.PostForm("name")
		password := c.PostForm("password")
		if len(name) == 0 || len(password) == 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "请输入正确的用户名或密码！"})
			return
		}
		user := database.Login(&database.User{Name: name, Password: password})
		token, err := jwt.GenerateToken(&jwt.User{UserName: user.Name, Id: user.Id})
		if err != nil {
			panic(err)
		}
		util.Success(
			c,
			&util.Result{
				Msg: "登录成功！",
				Data: gin.H{
					"token":    token,
					"userInfo": user,
				},
			})
	})
	// 注册
	g.POST("/register", func(c *gin.Context) {
		name := c.PostForm("name")
		password := c.PostForm("password")
		if len(name) == 0 || len(password) == 0 {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg":     "用户名和密码不能为空！",
				"data":    nil,
				"success": false,
			})
			return
		}
		user := database.User{
			Name:     name,
			Password: password,
		}
		db, err := database.GetDBInstance()
		if err != nil {
			panic("数据库链接出错！")
		}
		result := db.Create(&user)
		if result.Error != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"msg":     result.Error,
				"data":    nil,
				"success": false,
			})
			return
		}
		fmt.Println(result)
		c.JSON(http.StatusOK, gin.H{
			"msg":     "新增成功！",
			"data":    nil,
			"success": true,
		})
	})
	// 登出
	g.GET("/logout", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"msg":     "退出成功！",
			"data":    nil,
			"success": true,
		})
	})
	// 注销
	g.POST("/logoff", func(c *gin.Context) {
		name := c.PostForm("name")
		if len(name) == 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "请输入正确的用户名！", Status: http.StatusForbidden})
			return
		} else if name == "admin" {
			util.Error(c, &util.Result{Data: nil, Msg: "管理员账号禁止注销！", Status: http.StatusForbidden})
			return
		}
		password := c.PostForm("password")
		if len(password) == 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "请输入正确的用户密码！", Status: http.StatusForbidden})
			return
		}
		id := c.PostForm("id")
		if len(id) == 0 {
			util.Error(c, &util.Result{Data: nil, Msg: "用户id不能为空！", Status: http.StatusForbidden})
			return
		}
		err := database.LogOff(&database.User{Name: name, Id: id, Password: password})
		if err != nil {
			util.Error(c, &util.Result{Data: nil, Msg: err.Error()})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"msg":     "注销成功！",
			"data":    nil,
			"success": false,
		})
	})
}
